package org.example.maibobo.decode;

import org.example.maibobo.encode.CheckAndResetTimeEncodeResponse;
import org.example.maibobo.encode.HelloCodeEncodeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartboot.socket.transport.AioSession;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.LocalDateTime;
import java.util.Arrays;

import static org.example.util.ProcessorUtil.calculateChecksum;
import static org.example.util.ProcessorUtil.encodeTimestamp;

public class AuthenticationDecode implements Decode {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationDecode.class);

    /**
     * 当次测量结果
     *
     * @param session
     * @param data
     */
    @Override
    public void decoder(AioSession session, byte[] data) throws IOException {
        // 使用ByteBuffer来解析数据
        ByteBuffer buffer = ByteBuffer.wrap(data);

        //解析 血压计发送身份验证信息

        // 解析前导码
        int leadingCode1 = buffer.get() & 0xFF;
        int leadingCode2 = buffer.get() & 0xFF;
        System.out.println("前导码1: 0x" + Integer.toHexString(leadingCode1));
        System.out.println("前导码2: 0x" + Integer.toHexString(leadingCode2));

        // 解析传输方式
        int transferMode = buffer.get() & 0xFF;
        System.out.println("传输方式: 0x" + Integer.toHexString(transferMode));

        // 解析协议版本号和软件版本号
        int protocolVersion = buffer.get() & 0xFF;
        int softwareVersion = buffer.get() & 0xFF;
        System.out.println("协议版本号: 0x" + Integer.toHexString(protocolVersion));
        System.out.println("软件版本号: 0x" + Integer.toHexString(softwareVersion));

        // 解析长度
        byte[] lengthByte = new byte[2];
        buffer.get(lengthByte);
        System.out.println("长度: ");
        for (byte code : lengthByte) {
            System.out.printf("%02X ", code & 0xFF);
        }

        // 解析数据类型
        int dataType = (buffer.get() & 0xFF);
        System.out.println("数据类型: 0x" + Integer.toHexString(dataType));

        // 解析设备公司编码
        int companyCode = (buffer.get() & 0xFF);
        System.out.println("设备公司编码: 0x" + Integer.toHexString(companyCode));

        // 解析设备类型
        int deviceType = (buffer.get() & 0xFF);
        System.out.println("设备类型: 0x" + Integer.toHexString(deviceType));

        // 解析设备型号
        int deviceModel = (buffer.get() & 0xFF);
        System.out.println("设备型号: 0x" + Integer.toHexString(deviceModel));

        // 解析设备编码
        byte[] deviceCode = new byte[7];
        buffer.get(deviceCode);
        System.out.print("设备编码: ");
        for (byte code : deviceCode) {
            System.out.printf("%02X ", code & 0xFF);
        }
        System.out.println();

        // 解析SIM卡号码
        byte[] simCardNumber = new byte[7];
        buffer.get(simCardNumber);
        System.out.print("SIM卡号码: ");
        for (byte number : simCardNumber) {
            System.out.printf("%02X ", number & 0xFF);
        }
        System.out.println();

        // 解析时间戳
        byte[] timestamp = new byte[5];
        buffer.get(timestamp);
        System.out.print("时间戳: ");
        for (byte time : timestamp) {
            System.out.printf("%02X ", time & 0xFF);
        }
        System.out.println();

        // 解析校验位
        byte checksum = buffer.get();
        System.out.println("校验位: 0x" + String.format("%02X", checksum & 0xFF));


        // 验证校验结果
        byte calculatedChecksum = calculateChecksum(data, 2, data.length - 1);
        boolean isValid = checksum == calculatedChecksum;


        //比对时间
        //时间戳
        //（5byte）
        //举例：19年2月1日9点16分,则0x13 0x02 0x01 0x09 0x11 十六进制，共5位
        //（年份只发送后2位，如2019年只发送19年，十六进制为0x13）
        if (Arrays.equals(encodeTimestamp(LocalDateTime.now()), timestamp)) {
            System.out.println("校验结果: " + (isValid ? "通过" : "失败"));
            //校验通过
            if (isValid) {
                //普通协议发送
                session.writeBuffer().write(HelloCodeEncodeResponse.encodeProtocol());
            }

        } else {
            // 校准协议发送
            session.writeBuffer().write(CheckAndResetTimeEncodeResponse.encodeProtocol());
        }
    }
}
